package com.zhao.dota.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhao.dota.common.contant.CommonConst;
import com.zhao.dota.contant.GameModelConst;
import com.zhao.dota.mapper.MatchMapper;
import com.zhao.dota.model.DotaMatch;
import com.zhao.dota.service.MatchService;
import com.zhao.dota.service.ReportService;
import com.zhao.dota.struct.MonthMatches;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.List;

@Service
public class MatchServiceImpl extends ServiceImpl<MatchMapper, DotaMatch> implements MatchService {

    @Resource
    private ReportService reportService;

    @Override
    public boolean save(DotaMatch dotaMatch) {
        LambdaQueryWrapper<DotaMatch> query = Wrappers.lambdaQuery(DotaMatch.class).eq(DotaMatch::getMatchId, dotaMatch.getMatchId());
        DotaMatch old = getOne(query);
        if (old == null) {
            return super.save(dotaMatch);
        }
        BeanUtil.copyProperties(dotaMatch, old, CommonConst.IGNORE_NULL_VALUE);
        dotaMatch.setId(old.getId());
        return updateById(old);
    }

    @Override
    public DotaMatch getByMatchId(Long matchId) {
        LambdaQueryWrapper<DotaMatch> query = Wrappers.lambdaQuery(DotaMatch.class).eq(DotaMatch::getMatchId, matchId);
        return getOne(query);
    }

    @Override
    public Double countTimeBySteamId(Long steamId, int limit) {
        return baseMapper.countTimeBySteamId(steamId, limit);
    }

    @Override
    public List<DotaMatch> getNormalMonthMatch(YearMonth yearMonth) {
        LocalDateTime startTime = yearMonth.atDay(1).atTime(6, 0);
        LocalDateTime endTime = yearMonth.plusMonths(1).atDay(1).atTime(6, 0);
        LambdaQueryWrapper<DotaMatch> query = Wrappers.lambdaQuery(DotaMatch.class).ge(DotaMatch::getEndTime, startTime)
                .le(DotaMatch::getEndTime, endTime)
                .notIn(DotaMatch::getGameMode, GameModelConst.MID_ONLY, GameModelConst.SOLO_MID_ONLY);
        List<DotaMatch> list = list(query);
        return list;
    }

    @Override
    public List<MonthMatches> monthMatches() {
        return baseMapper.monthMatches();
    }
}
